<template>
  <div>
    <common-head title="联系人列表"></common-head>
    <div class="wrap">
       <van-address-list
          v-model="chosenAddressId"
          :list="list"
          default-tag-text="默认"
          @add="onAdd"
          @edit="onEdit"
          @select="choseLinkman"
        />
    </div>
  </div>
</template>

<script>
import CommonHead from '@components/CommonHead'
import { showLinkmanAdd } from '@api'
export default {
  data () {
    return {
      chosenAddressId: '1',
      list: []
    }
  },
  created () {
    this.showLinkmanAdd()
  },
  beforeRouteEnter (to, from, next) {
    localStorage.setItem('from', from.path)
    next()
  },
  methods: {
    choseLinkman (linkman, index) {
      const from = localStorage.getItem('from')
      if (from === '/confirmOrder') {
        // 从确认订单页过来
        this.$router.push({
          path: from,
          query: {
            id: linkman.id
          }
        })
      }
    },
    onAdd () {
      this.$router.push('/addLinkman')
    },
    onEdit (linkman) {
      this.$router.push({
        path: '/editLinkman',
        query: {
          id: linkman.id
        }
      })
    },
    showLinkmanAdd () {
      showLinkmanAdd({
        token: localStorage.getItem('token')
      }).then(res => {
        if (res.data.code === 0) {
          const linkmen = res.data.data.result
          const linkmanArr = []
          linkmen.forEach(linkman => {
            // 循环每个联系人 所有的key
            const obj = {}
            for (const key in linkman) {
              switch (key) {
                case 'id':
                  obj.id = linkman[key]
                  break
                case 'linkMan':
                  obj.name = linkman[key]
                  break
                case 'mobile':
                  obj.tel = linkman[key]
                  break
                case 'address':
                  obj.address = linkman[key]
                  break
                case 'isDefault':
                  obj.isDefault = linkman[key]
                  break
                default:
                  break
              }
            }
            linkmanArr.push(obj)
          })
          this.list = linkmanArr
          // 判断是否有默认联系人 有展示默认  没有选中第一个
          const linkman = this.list.find(linkman => linkman.isDefault)
          if (linkman) {
            this.chosenAddressId = linkman.id
          } else {
            this.chosenAddressId = this.list[0].id
          }
        }
      })
    }
  },
  components: {
    CommonHead
  }
}
</script>

<style lang="scss" scoped>
.wrap{
  padding-top:50px;
  background-color: #fff;
}
</style>
